
var tools = require('./toolboxTools.js');
let appNames = ["X浏览器", "#N1 X浏览器", "#N2 X浏览器", "#N3 X浏览器", "#N4 X浏览器", "#N5 X浏览器", "#N6 X浏览器", "#N7 X浏览器", "#N8 X浏览器"]
//当前任务执行次数
let num = 1;
//任务截图保存路径
let imgPath = "/sdcard/$MuMu12Shared/Screenshots/";
//当前执行浏览器
let app = null;
//执行火爆的任务
let paddles = [];
//起始浏览器
let startIndex = 0;
function main(params) {
    tools.init()
    if(params.startIndex != undefined){
      startIndex = parseInt(params.startIndex)
      if(startIndex > 0){
        appNames.splice(0,startIndex);
      }
    }
    // toastLog(hasText("启动"))
    while (true) {
        if (num >= 2) {
            break;
        }
        paddles = []
        for (var i = 0; i < appNames.length; i++) {
            app = appNames[i]
            opneApp(app)
            toastLog(`${app}执行第${num}遍任务结束`)
        }
        home()
        deletePaddle()
        toastLog(`所有任务执行结束`)
        num++
    }
    exit()
}

//删除执行火爆的任务
function deletePaddle() {
    for (let i = 0; i < paddles.length; i++) {
        //删除appNames里面包含的值
        for (let j = 0; j < appNames.length; j++) {
            if (appNames[j].includes(paddles[i])) {
                appNames.splice(j, 1);
                toastLog(`删除${paddles[i]}任务`);
                j--;
            }
        }
    }
}
//启动
function opneApp() {
    home()
    sleep(1000)
    home()
    sleep(1000)
    var returned = text(app).findOne(500);
    if (returned) {
        press(returned.bounds().centerX() + random(-5, 5), returned.bounds().centerY() + random(-5, 5), 50);
        sleep(500);
        startHome(app)
        return true;
    } else {
        toastLog(`打开${app}失败`);
    };
    return false;
}

//进入首页
function startHome() {
    sleep(3000)
    let texts = tools.ocrText()
    //登录状态
    let login = true;
    //主页状态
    let home = false;
    //开始任务状态
    let st = false;
    //京东主页坐标
    let homeCoordinate = {};
    //是否已经开启任务
    let start1 = false;
    for (let i = 0; i < texts.length; i++) {
        let returned = texts[i]
        if (returned.words.indexOf("我的") != -1) {
            login = true;
        } 
        if (returned.words.indexOf("未登录") != -1) {
            login = false;
        }  else if (returned.words === "京东") {
            homeCoordinate.x = tools.getCenterPoint(returned.location).x;
            homeCoordinate.y = tools.getCenterPoint(returned.location).y - 30;
            home = true;
        }else if (returned.text === "开启任务") {
            toastLog("已进入首页")
            st = true;
        }else if (returned.text === "停止任务") {
            toastLog("已开启任务")
            start1 = true;
        }
    }
    if(login){
      if(st === false){
        if(home){
            press(homeCoordinate.x,homeCoordinate.y,50);
            toastLog("正在进入首页1")
            sleep(4000)
        }else{
            press((427+532)/2,(892+952)/2,50);
            sleep(1000)
            tools.clickTextByOcr("京东")
            toastLog("正在进入首页2")
            sleep(4000)
        }
      }
    }else{
        paddles.push(app)
        toastLog("未登录")
        killApp()
        return false;
    }
    if(start1){
        waitOver()
        killApp()
    }else{
        start()
    }
    return true;
}

//开始任务
function start() {
    if (tools.clickTextByOcr("开启任务") === false) {
        toastLog("开启任务失败")
        return false;
    }
    sleep(500)
    if (tools.clickTextByOcr("确定") === false) {
        toastLog("确定开启任务失败")
        return false;
    }
    waitOver()
    killApp()
    return true;
}

//等待任务结束
function waitOver() {
    sleep(3000)
    let timeout = 1000 * 60 * 10
    let startTime = new Date().getTime();
    while (true) {
        if (new Date().getTime() - startTime > timeout) {
            toastLog(`任务执行超时`);
            tools.clickTextByOcr("停止任务")
            sleep(1000)
            tools.clickTextByOcr("确定")
            sleep(2000)
            break;
        }
        let res = tools.ocrText();
        let stop = false;
        for (let i = 0; i < res.length; i++) {
            let text = res[i].words
            let centerX = tools.getCenterPoint(res[i].location).x
            let centerY = tools.getCenterPoint(res[i].location).y
            if (text.includes("给5星")) {
                click(centerX,centerY)
            }
            if (text.includes("请休息1天") || text.includes("更换账号") && centerX < (device.width / 2) && centerY > (device.height / 2)) {
                paddles.push(app)
                stop = true
                toastLog("任务已做完")
                saveImg()
                break
            }
            if (text.includes("未登录")) {
                paddles.push(app)
                stop = true
                toastLog("未登录")
                break
            }
            if (text.includes("任务已停止") && centerX < (device.width / 2) && centerY > (device.height / 2)) {
                stop = true
                toastLog("任务已停止")
                saveImg()
                break
            }
            if (text == "确定") {
                toastLog(`${app}插件异常,开始重启插件`);
                click(centerX,centerY)
                sleep(2000)
                restart()
            }
            if (text.includes("快速验证")) {
                closeVerify()
                toastLog(`出现快速验证`);
                stop = true
                break
            }
        }
        if (stop) {
            break
        } else {
            toastLog(`${app}执行第${num}遍任务中`)
        }
    }
    return true
}

//关闭验证
function closeVerify() {
    back()
    sleep(5000)
    if (tools.clickTextByOcr("停止任务") === false) {
        back()
        sleep(3000)
        if (tools.clickTextByOcr("停止任务") === false) {
            back()
            sleep(3000)
        }
    }
    tools.clickTextByOcr("确定")
    sleep(2000)
}

//关闭浏览器
function killApp() {
    sleep(1000)
    click((217 + 322) / 2, (892 + 952) / 2)
    sleep(1000)
    click((360 + 540) / 2, (888 + 960) / 2)
    sleep(1000)
}

//插件异常重启
function restart() {
    tools.clickTextByOcr("停止任务")
    sleep(3000)
    tools.clickTextByOcr("确定")
    sleep(6000)
    tools.clickTextByOcr("开启任务")
    sleep(3000)
    tools.clickTextByOcr("确定")
    sleep(2000)
}

//保存当前任务截图
function saveImg() {
    try {
        tools.clickTextByOcr("我的")
        sleep(3000)
        let img = captureScreen();
        let time = new Date().getTime();
        let path = `${imgPath}/${tools.timestampToDateString(time)}/`;
        files.createWithDirs(path)
        time = new Date(time);
        var hour = time.getHours().toString().padStart(2, "0");
        var minute = time.getMinutes().toString().padStart(2, "0");
        var second = time.getSeconds().toString().padStart(2, "0");
        let runTarget = getFinishTaskNum()
        path = `${path}${hour}-${minute}-${second}-${app}-${runTarget}.jpg`;
        images.save(img, path);
        img.recycle();
    } catch (e) {
        log(e)
        toastLog(`保存截图失败`);
    }
}

//获取当前完成的任务数量
function getFinishTaskNum() {
    //已完成的任务数
    let num = null;
    let texts = tools.ocrText()
    for (let i = 0; i < texts.length; i++) {
        let returned = texts[i]
        if (returned.words.includes("已完成") && returned.words.includes("条")) {
            num = parseInt(returned.words.match(/\d+/));
            break;
        }
    }
    return num;
}
exports.main = main;
// main()